using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using NAst.Common;
using System.Xml;
using System.Diagnostics;
using System.IO;
using System.Configuration;

namespace NAstAp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            NetworkAwareAssistant.ConfigurationLoaded += new EventHandler(NetworkAwareAssistant_ConfigurationLoaded);
            NetworkAwareAssistant.ConfigurationChanged += new NAAConfigurationChangeEventHandler(NetworkAwareAssistant_ConfigurationChanged);
            NetworkAwareAssistant.NetworkAddressChanged += new EventHandler(NetworkAwareAssistant_NetworkAddressChanged);
            NetworkAwareAssistant.ExceptionsRaised += new NAAExceptionEventHandler(NetworkAwareAssistant_ExceptionsRaised);
            NetworkAwareAssistant.Initialize();
            ((ToolStripMenuItem)contextMenuStrip1.Items[5]).Checked = Properties.Settings.Default.Debug;
            string confFile = NetworkAwareAssistant.FindConfigDocument();
            FileSystemWatcher fileWatcher = new FileSystemWatcher(confFile.Substring(0, confFile.LastIndexOf('\\')), confFile.Substring(confFile.LastIndexOf('\\') + 1));
            fileWatcher.Changed += new FileSystemEventHandler(FileChanged);
            fileWatcher.EnableRaisingEvents = true;
            this.Resize +=new EventHandler(Form1_Resize);
            this.Hide();
        }

        void NetworkAwareAssistant_ConfigurationChanged(object sender, NAAConfigurationChangeEventArgs e)
        {
            notifyIcon1.ShowBalloonTip(30000, "Change configuration", "New configuration applied", ToolTipIcon.Info);
            if (e.ActiveConfiguration != null)
            {
                notifyIcon1.Text = "Active configuration: " + e.ActiveConfiguration.Name;
            }
            else
            {
                notifyIcon1.Text = "No active configuration";
            }
            foreach (ToolStripItem it in contextMenuStrip1.Items)
            {
                if (!(it is ToolStripMenuItem))
                    continue;
                if (it.Tag == e.ActiveConfiguration)
                    (it as ToolStripMenuItem).Checked = true;
                else
                    (it as ToolStripMenuItem).Checked = false;
            }
        }

        void NetworkAwareAssistant_NetworkAddressChanged(object sender, EventArgs e)
        {
            notifyIcon1.ShowBalloonTip(30000, "Change configuration", "Network address changed", ToolTipIcon.Info);
            notifyIcon1.Text = "Testing configurations...";
        }

        void NetworkAwareAssistant_ConfigurationLoaded(object sender, EventArgs e)
        {
            for (int i = contextMenuStrip1.Items.Count-1; i >=7 ; i--)
                contextMenuStrip1.Items.RemoveAt(i);
            notifyIcon1.ShowBalloonTip(30000, "Change configuration", "Loading...", ToolTipIcon.Info);
            foreach (NetworkConfiguration cfg in NetworkAwareAssistant.Configurations)
            {
                ToolStripMenuItem it = new ToolStripMenuItem();
                it.Text = cfg.Name;
                it.Click += new EventHandler(configuration_Clicked);
                it.Tag = cfg;
                contextMenuStrip1.Items.Add(it);
            }
        }

        void configuration_Clicked(object sender, EventArgs e)
        {
            ToolStripMenuItem it = sender as ToolStripMenuItem;
            if (it == null || it.Tag == null || !(it.Tag is NetworkConfiguration))
                return;

            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
            this.notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon1.Icon")));
            this.notifyIcon1.Text = "Loading...";
            notifyIcon1.ShowBalloonTip(30000, "Change configuration", "Loading...", ToolTipIcon.Info);
            NetworkConfiguration cfg = it.Tag as NetworkConfiguration;
            NetworkAwareAssistant.Change(cfg);
        }

        void NetworkAwareAssistant_ExceptionsRaised(object sender, NAAExceptionEventArgs e)
        {
            StringBuilder blrMessage = new StringBuilder();

            foreach (Exception ex in e.Exceptions)
            {
                if (blrMessage.Length > 0)
                    blrMessage.Append("\r\n");
                blrMessage.Append(ex.Message);
            }

            notifyIcon1.ShowBalloonTip(30000, e.ErrorTitle,blrMessage.ToString(), ToolTipIcon.Error);
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void configureToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ProcessStartInfo pi = new ProcessStartInfo();
            pi.Arguments = NetworkAwareAssistant.FindConfigDocument();
            pi.FileName = "notepad.exe";
            pi.WindowStyle = ProcessWindowStyle.Normal;

            Process p = Process.Start(pi);
            ConfigEdit config = new ConfigEdit();
            config.ShowDialog();
        }

        private void forcetestToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
            notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon1.Icon")));
            notifyIcon1.Text = "Loading...";
            notifyIcon1.ShowBalloonTip(30000, "Change configuration" , "Testing...", ToolTipIcon.Info);
            NetworkAwareAssistant.Change();
        }

        private void FileChanged(object sender, FileSystemEventArgs e)
        {
            NetworkAwareAssistant.Terminate();
            notifyIcon1.ShowBalloonTip(30000, "Change configuration" , "Restarting...", ToolTipIcon.Info);
            NetworkAwareAssistant.ReInitialize();
        }

        private void debugToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (((ToolStripMenuItem)sender).Checked)
            {
                ((ToolStripMenuItem)sender).Checked = false;
                Properties.Settings.Default.Debug = false;
            }
            else
            {
                ((ToolStripMenuItem)sender).Checked = false;
                Properties.Settings.Default.Debug = false;
            }
            Properties.Settings.Default.Save();
        }
        /// <summary>
        /// Occurs when Form is shown for the first time. Minimizes the form to tray.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Shown(object sender, EventArgs e)
        {
            Visible = false; // inhibit the minimizing animation
            WindowState = FormWindowState.Minimized; // Resize event triggered automatically
        }

        /// <summary>
        /// Occurs on resizing. Toggles between form and tray icon.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Resize(object sender, EventArgs e)
        {
            if (FormWindowState.Minimized == WindowState)
            {
                Hide(); // leave only the sys tray icon
                notifyIcon1.Visible = true;
            }
            else
            {
                notifyIcon1.Visible = false;
            }
        }
    }
}